package util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {
	private static int default_age=30*60;
	private static String default_path="/shopping";
	public static void saveCookie(String name, String value,
			HttpServletResponse response, int maxAge) throws UnsupportedEncodingException {
		String value2=URLEncoder.encode(value, "utf-8");
		Cookie cookie = new Cookie(name, value2);
		cookie.setMaxAge(maxAge);
		cookie.setPath(default_path);
		response.addCookie(cookie);
	}

	public static void saveCookie(String name, String value,
			HttpServletResponse response) throws UnsupportedEncodingException {
		saveCookie(name,value,response,default_age);
	}

	public static String getCookie(String name, HttpServletRequest request) throws UnsupportedEncodingException{
		Cookie[] cookies=request.getCookies();
		if(cookies!=null){
			for (Cookie c : cookies) {
				if(name.equals(c.getName())){
					return URLDecoder.decode(c.getValue(), "utf-8");
				}
			}
		}
		return null;
	}

	public static void delete(String name, HttpServletResponse response){
		Cookie cookie = new Cookie(name,"");
		cookie.setMaxAge(0);
		cookie.setPath(default_path);
		response.addCookie(cookie);
	}
}
